import {objectIsEq, resetLongToStr} from "@/utils/biz/common/BizUtils";
import {UserRoomApi} from "@/api/user_api";
import {AndroidSDK} from "@/sdk/AndroidSdkService";
import {Observer} from "@/utils/observer/Observer";
/**
 * 诊室屏 公共业务抽象 实现类 可以再改写其他的
 */
class WindowCommonObserverBiz extends Observer{
  constructor(self, deviceInfo = {}, item) {
    super();
    // 外部组件
    this.catcheInfo = self;
    // 设备信息
    this.deviceInfo = deviceInfo;
    // 当前组件信息
    this.currentInfo = item || {};
    console.log(this.deviceInfo, "this.deviceInfo");
  }
  /**
   * 消息监听入口
   * @param bizType
   * @param msgContent
   */
  update(bizType,msgContent) {
    // 在这里显示监听的消息
    if (this[bizType]){
      this[bizType](msgContent);
    }
  }

  /**
   * 初始化
   */
  async init() {
    await Promise.all([
      this.roomGetLoginDoc(),
      this.roomHeaderGetDeptInfo(),
      this.setHeadTitle(this.deviceInfo.deviceName)
    ]);
  }
  /**
   * 暂停
   * @param obj
   */
  pauseDoctor(obj) {
    this.pauseOrCancel(obj,true)
  }

  /**
   * 取消暂停
   * @param obj
   */
  cancelPause(obj) {
    this.pauseOrCancel(obj,false)
  }

  /**
   * 暂停/取消暂停
   * @param str
   * @param bool
   */
  pauseOrCancel(str, bool) {
    const obj = JSON.parse(resetLongToStr(str));
    let self = this.catcheInfo;
    self.roomScreenData.workerInfoList.map((item) => {
      // 满足条件的医生
      if (item.workerId === obj.msgContent.workerId && item.workStationId === obj.msgContent.terminalId) {
        item.isPause = bool;
        item.onlineStatus = bool ? "1" : "0";
      }
    });
    // 写入全量数据
    this.roomSetDataListWidthFullData();
    self.pauseLayerInfo.visible = bool;
  }

  /**
   * 医生登录消息
   * @returns {Promise<void>}
   * @param str
   */
  async doctorLogin(str) {
    try {
      let self = this.catcheInfo;
      const obj = JSON.parse(resetLongToStr(str));
      // 兼容协议上屏
      if (Number(Number(self.apiType)) === 0) {
        await this.roomGetPatients([obj.msgContent.terminalId]);
      } else {
        await this.roomGetPatients([obj.msgContent.workerId]);
      }

    } catch (e) {
      console.error(e);
    }
  }

  /**
   * 医生退出消息
   * @param str
   */
  doctorLogout(str) {
    const obj = JSON.parse(resetLongToStr(str));
    let self = this.catcheInfo;
    // Q：为什么要占位
    // A: 如果是多人屏，第一个医生退出了，第二个医生是要继续在原位置的，第一个医生再次登陆，还可以占原先的位置
    self.roomScreenData.workerInfoList.map((item, index) => {
      if (item.workStationId === obj.msgContent.terminalId) {
        self.roomScreenData.workerInfoList.splice(index, 1, self.roomScreenData.workerInfo);
      }
    });
    // 医生退出 发送全量接口数据
    this.roomSetDataListWidthFullData();
    // 医生退出 关闭暂停接诊
    self.pauseLayerInfo.visible = false;
  }

  /**
   * 刷新消息
   * @param str
   * @returns {Promise<boolean>}
   */
  async refreshMsg(str) {
    let self = this.catcheInfo;
    try {
      // 都不在屏上就刷新全量数据
      if (false === this.checkIsHaveWorker()) {
        await this.roomGetLoginDoc();
        return false;
      }
      // 防止消息过多，增加一层判定
      const obj = JSON.parse(resetLongToStr(str));
      if (obj.msgContent && obj.msgContent['typeList']) {
        if (obj.msgContent['typeList'].includes("SIGN_REFRESH")) {
          if (self.roomScreenData.waitPatientType === "1" || self.roomScreenData.waitNum === 0) {
            return false;
          }
        }
        if (obj.msgContent['typeList'].includes("WAIT")) {
          // 诊室屏 刷新消息
          const workerIdList = this.userWaitingGetWorkers(self.roomScreenData.workerInfoList, obj.msgContent.registerObjId);
          // 刷新患者数据
          self.roomScreenData.workerIdList = workerIdList || [];
          await this.roomGetPatients(self.roomScreenData.workerIdList);
        }
      }
    } catch (e) {
      self.handleException("sdkBizServices", "MtUserWaitingRefresh -> 诊室刷新异常", JSON.stringify(e.stack));
    }
  }

  /**
   * 更新患者信息
   * @param str
   */
  updateDoctorPatients(str) {
    let self = this.catcheInfo;
    if (Number(self.apiType) !== 0) {
      const obj = JSON.parse(resetLongToStr(str));
      self.roomScreenData.workerInfoList.map((item) => {
        // 兼容协议上屏
        if (Number(Number(self.apiType)) === 0) {
          if (item.workStationId === obj.msgContent.terminalId) {
            item.treatingPatient = obj.treatingPatient || [];// 正在就诊患者
            item.waitingPatientList = obj.msgContent.waitingPatientList || [];
          }
        } else if (item.workerId === obj.msgContent.workerId) {
          let tempTreatingPatient = [];
          if (obj.msgContent.treatingPatient) {
            if (objectIsEq(obj.msgContent.treatingPatient, "Array")) {
              tempTreatingPatient = obj.msgContent.treatingPatient;
            } else {
              tempTreatingPatient.push(obj.msgContent.treatingPatient);
            }
          }
          item.treatingPatient = tempTreatingPatient;// 正在就诊患者
          item.waitingPatientList = obj.msgContent.waitingPatientList || [];
        }

      });
      // 发送更新患者数据
      this.roomSetDataListWidthFullData();
    }
  }

  /**
   * 候诊屏 -- 获取满足条件的医生ID
   * @param arr
   * @param rid
   * @returns {*[]}
   * @constructor
   */
  userWaitingGetWorkers(arr, rid) {
    const worker = [];
    let self = this.catcheInfo;
    arr.map((item) => {
      if (item.registerObjIdList && item.registerObjIdList.includes(rid)) {
        // 兼容协议上屏
        if (Number(Number(self.apiType)) === 0) {
          worker.push(item.workStationId);
        } else {
          worker.push(item.workerId);
        }

      }
    });
    return worker;
  }

  /**
   * 检查医生是否在屏上
   */
  checkIsHaveWorker() {
    let isCheck = true;
    let self = this.catcheInfo;
    if (Number(Number(self.apiType)) === 0) {
      let workerList = [];
      self.roomScreenData.workerInfoList.map((item) => {
        if (item.workStationId !== "") {
          workerList.push(item.workStationId);
        }
      });
      if (workerList.length === 0) {
        isCheck = false;
      }
    }
    return isCheck;
  }

  /**
   * 页面第一次加载时获取登陆医生
   * @returns {Promise<void>}
   * @constructor
   */
  async roomGetLoginDoc() {
    let self = this.catcheInfo;
    const res = await UserRoomApi.getRoomDocs({
      terminalId: self.deviceInfo.screenId,
      terminalType: self.deviceInfo.screenType,
      businessType: self.deviceInfo.businessType,
      tenantId: self.deviceInfo.hospitalId,
      dataSource: Number(self.apiType) || "0",
    });
    if (res.code === 200) {
      const workerIdListInfo = res.data || [];
      // 获取登录医生 这里返回的参数workerId 代表是工作站ID 切记不要混淆
      const docIdArr = workerIdListInfo.map((item) => item.workerId);

      self.roomScreenData.workerIdList = docIdArr || [];
      // 获取患者数据
      await this.roomGetPatients(self.roomScreenData.workerIdList);
    } else {
      AndroidSDK.writeLog("getLoginDoc--->" + JSON.stringify(res));
    }
  }

  /**
   * 获取患者数据
   * @param workStationIdList
   * @returns {Promise<boolean>}
   * @constructor
   */
  async roomGetPatients(workStationIdList = []) {
    try {

      if (!workStationIdList || workStationIdList.length === 0) {
        return false;
      }
      let self = this.catcheInfo;

      const {data, code} = await UserRoomApi.getRoomPatients({
        terminalId: self.deviceInfo.screenId,
        terminalType: self.deviceInfo.screenType,
        businessType: self.deviceInfo.businessType,
        tenantId: self.deviceInfo.hospitalId,
        // 后台参数这里代表叫号器ID
        workerIdList: workStationIdList,
        dataSource: Number(self.apiType) || "0",
        // 查询类型
        waitPatientType: self.roomScreenData.waitPatientType,
        // 等候人数
        waitNum: self.roomScreenData.waitNum || 0
      });
      let tempDataArr = [];
      if (code === 200 && data && data.length > 0) {
        data.map((item) => {
          const workerInfo = {
            workerId: item.workerId, // 医生ID
            workStationId: item.workStationId,// 医生工作站ID
            workStationName: item.workStationName || "",// 医生工作站
            registerObjIdList: item.registerObjIdList || [],
            workerName: item.workerName, // 医生姓名
            workerPicture: item.workerPicture, // 医生照片
            workerBusinessCard: item.workerBusinessCard,// 医生二维码
            workerTitle: item.workerTitle, //医生职称
            workerIntro: item.workerIntro, //医生简介
            workerDegree: item.workerDegree,// 学历
            workerSpecialty: item.workerSpecialty,// 医生擅长
            deptName: item.deptName, // 医生所属科室
            isPause: item.onlineStatus === "1", // 暂停接诊状态
            onlineStatus: item.onlineStatus,
            preTreatingPatient: [],// 上一个正在就诊
            treatingPatient: item.treatingPatient || [],// 正在就诊患者
            waitingPatientList: item.waitingPatientList || [], // 等候就诊患者
            // 通用排班
            weekInfo: [],
            // 原始数据
            scheduleList: []
          };
          tempDataArr.push(workerInfo);
        });
      }
      // 双重校验
      tempDataArr.forEach((workerInfo) => {
        let index = self.roomScreenData.workerInfoList.findIndex((item) => {
          if (item.workStationId && item.workStationId !== "") {
            return Number(workerInfo.workStationId) === Number(item.workStationId);
          } else {
            return Number(workerInfo.workerId) === Number(item.workerId);
          }
        });
        if (index > -1) {
          // 直接赋值
          let oldWorkerInfo = self.roomScreenData.workerInfoList[index];
          let treatingPatient = oldWorkerInfo.treatingPatient;
          let preTreatingPatientOld = oldWorkerInfo.preTreatingPatient;
          if (treatingPatient && treatingPatient.length > 0) {
            let preTreatingPatient = [];
            for (let i = 0; i < treatingPatient.length; i++) {
              preTreatingPatient.push({
                orderNo: "",
                patientName: "",
                registerObjName: treatingPatient[i].registerObjName || "",
                registerObjSimpleName: treatingPatient[i].registerObjSimpleName || "",
                registerObjGroupName: treatingPatient[i].registerObjGroupName || "",
                registerObjGroupSimpleName: treatingPatient[i].registerObjGroupSimpleName || ""
              });
            }
            workerInfo.preTreatingPatient = preTreatingPatient;
          } else {
            // 不存在就读取上一个的
            workerInfo.preTreatingPatient = preTreatingPatientOld;
          }

          // 直接赋值
          self.roomScreenData.workerInfoList[index] = workerInfo;
        } else {
          for (let i = 0; i < self.roomScreenData.workerInfoList.length; i++) {
            if (self.roomScreenData.workerInfoList[i].workerId === "") {
              self.roomScreenData.workerInfoList[i] = workerInfo;
              break;
            }
          }
        }
      });
      // 写入全量数据
      this.roomSetDataListWidthFullData();

      self.roomScreenData.workerInfoList.forEach((item,index) =>{
        if(item.onlineStatus === '1'){
          // 窗口屏 更新在线状态
          self.pauseLayerInfo.visible = item.isPause;
        }
      })
    } catch (e) {
      console.error(e);
    }
  }

  /**
   * 写入数据
   */
  roomSetDataListWidthFullData() {
    let self = this.catcheInfo;
    try {
      let fullData = self.roomScreenData.workerInfoList;
      let formRef;
      formRef = self.$refs["vFormRef"];
      formRef.executeChildMethod(this.currentInfo?.id, "roomDoctorInfo", fullData);
    } catch (e) {
      self.handleException("sdkBizServices", "内部组件异常 -- roomDoctorInfo -- >", JSON.stringify(e.stack));
    }
  }


  /**
   * 打开弹窗
   * @param str
   */
  async openMsgWin(str) {
    const obj = JSON.parse(resetLongToStr(str));
    let self = this.catcheInfo;
    // 弹窗需要原始数据
    self.msgWinData.data = obj;
    self.msgWinData.treatingAlert = obj.msgContent.treatingAlert;
    self.msgWinData.waitingAlert = obj.msgContent.waitingAlert;
    let treatingPatientList = obj.msgContent.treatingPatientList;
    if (treatingPatientList) {
      self.msgWinData.currPatient = treatingPatientList || [];
    }else{
      self.msgWinData.currPatient = obj.msgContent.treatingPatient?[obj.msgContent.treatingPatient] : [];
    }
    self.msgWinData.waitPatient = obj.msgContent.waitingPatientList;
    // 配置是否展示就诊弹窗/候诊弹窗
    self.hasCallShow = !!(obj.msgContent.treatingAlert || obj.msgContent.waitingAlert);
  }

  /**
   * 关闭弹窗
   */
  closeMsgWin() {
    let self = this.catcheInfo;
    self.hasCallShow = false;
  }

  /**
   * 顶部科室信息
   */
  async roomHeaderGetDeptInfo() {
    let self = this.catcheInfo;
    const {data, code} = await UserRoomApi.getRoomDeptInfo({
      terminalId: self.deviceInfo.screenId,
      terminalType: self.deviceInfo.screenType,
      businessType: self.deviceInfo.businessType,
      tenantId: self.deviceInfo.hospitalId,
      dataSource: Number(self.apiType) || "0",
    });
    if (code === 200) {
      self.roomScreenData.roomDeptInfo.deptName = data.deptName || '';
      self.roomScreenData.roomDeptInfo.deptShortName = data.deptShortName || '';
      // 屏幕所属科室
      self.roomScreenData.roomDeptInfo.oldDeptName = data.oldDeptName || '';
      self.roomScreenData.roomDeptInfo.oldDeptShortName = data.oldDeptShortName || '';

      self.roomScreenData.roomDeptInfo.roomName = data.treatmentRoomName || '';
      self.roomScreenData.roomDeptInfo.roomNo = data.treatmentRoomNumber || '';
      self.roomScreenData.roomDeptInfo.roomShortName = data.treatmentRoomShortName || '';
      self.roomScreenData.roomDeptInfo.deptIntroduction = data['introduction'] || '';
      for (let key in data) {
        if (!self.roomScreenData.roomDeptInfo.hasOwnProperty(key)) {
          self.roomScreenData.roomDeptInfo[key] = data[key];
        }
      }
      // 写入头部科室、诊室 名称
      this.roomSetDataListWidthDeptInfo();
    }
  }
   /**
   * 设置头部组件的名称
   */
   setHeadTitle(str) {
    // 通过索引获取坐标
    let headerItem = this.catcheInfo.modelMap["header"];
    let self = this.catcheInfo;
    if (headerItem && headerItem.options.config) {
      let configObj = headerItem.options[headerItem.options.config];
      if (!configObj.content || configObj.content === "") {
        if (str && true === self.trendsKey) {
          configObj.content = str || "";
        } else {
          configObj.content = self.deviceInfo.deviceName || "";
        }
      } else {
        if (str && true === self.trendsKey) {

          configObj.content = str || "";
        }
      }
    }
  }

  /**
   * 写入科室信息
   */
  roomSetDataListWidthDeptInfo(){
    let self = this.catcheInfo;
    try {
      const formRef = self.$refs['vFormRef'];
      if (formRef) {
        formRef.executeChildMethod(this.currentInfo?.id, 'roomDeptInfo', self.roomScreenData.roomDeptInfo);
        // alert(JSON.stringify(self.roomScreenData.roomDeptInfo));
      }
    } catch (e) {
      self.handleException('sdkBizServices', '内部组件异常 -- roomDeptInfo[roomSetDataListWidthDeptInfo] -- >', JSON.stringify(e.stack));
    }
  }
}

export {WindowCommonObserverBiz};
